package leetcode.editor.cn;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class AddTwoNumbers {
    public static void main(String[] args) {
        Solution solution = new AddTwoNumbers().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)


    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode head = null, cur = null;
            ListNode node1 = l1, node2 = l2;
            int temp = 0;
            while (node1 != null || node2 != null) {
                int n1 = l1 == null ? 0 : l1.val;
                int n2 = l2 == null ? 0 : l2.val;

                int sum = n1 + n2 + temp;
                if (head == null) {
                    head = cur = new ListNode(sum % 10);
                }else {
                    cur = new ListNode(sum % 10);
                    cur = cur.next;
                }

                if (l1 != null) l1 = l1.next;
                if (l2 != null) l2 = l2.next;
            }

            // 处理最后进位的temp
            if (temp > 0) {
                cur.next = new ListNode(temp);
            }
            return head;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
